package com.tbit.uqbike.client.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: chen
 * @Description: 人脸识别工具类
 * @Date: 创建于 15:18 2021/1/26
 */
@Slf4j
public class FaceUtil {

    private static final String IMAGE_BASE_64_START = "data:";

    /**
     * 本地图片转base64编码
     *
     * @param filePath 文件图片所在路径
     * @return base64编码
     */
    public static String imageToBase64(String filePath) throws Exception {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        String encode = "";
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            encode = Base64.encode(bytes);
        } catch (Exception e) {
            throw e;
        }
        return encode;
    }

    /**
     * base64转字节流
     * @param base64Str
     * @return
     */
    public static InputStream base64ToInputStream(String base64Str){
        ByteArrayInputStream stream = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bt = decoder.decodeBuffer(base64Str);
            stream = new ByteArrayInputStream(bt);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return stream;
    }
    /**
     * 转换
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String convert(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            fileInputStream.read(bytes);
            fileInputStream.close();
            return Base64.encode(bytes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    /**
     * 拼接图片前缀
     *
     * @param imageBase64 图片的base64编码
     * @return 图片base64编码(带前缀)
     */
    public static String concatImagePrefix(String imageBase64) {
        if (StringUtils.isBlank(imageBase64)) {
            return imageBase64;
        }
        if (imageBase64.contains(IMAGE_BASE_64_START)) {
            return imageBase64;
        }
        return "data:image/jpg;base64," + imageBase64;
    }

    /**
     * remove image prefix
     *
     * @param imageBase64 图片的base64编码
     * @return 图片base64编码(不带前缀)
     */
    public static String removeImagePrefix(String imageBase64) {
        if (StringUtils.isBlank(imageBase64)) {
            return imageBase64;
        }
        return imageBase64.substring(imageBase64.indexOf(",") + 1);
    }

    /**
     * 图片人脸认证
     *
     * @param appcode   唯一标识
     * @param base64Str 图片base64地址字符串
     * @param name      姓名
     * @param idNO      身份证号
     * @return
     * @throws Exception
     */
    public static String face(String appcode, String base64Str, String name, String idNO, Map<String, Object> pushMap) {

        String host = "https://zfah.market.alicloudapi.com";
        String path = "/efficient/idfaceIdentity";
        String method = "POST";
        //String appcode = "5d086f81e4924fcdbf823659c8db2ccc";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();

        bodys.put("base64Str", base64Str);
        /**0 非活体认证*/
        bodys.put("liveChk", "0");
        bodys.put("name", name);
        bodys.put("number", idNO);

        pushMap.put("request_result", false);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //System.out.println(response.toString());
            pushMap.put("request_result", true);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            return EntityUtils.toString(response.getEntity());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 将图片转换成Base64编码
     *
     * @param imgFile 待处理图片地址
     * @return
     */
    public static String getImgBase(String imgFile) {
        // 将图片文件转化为二进制流
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        // 图片头
        //String imghead = "data:image/jpeg;base64,";
        return org.apache.commons.codec.binary.Base64.encodeBase64String(data);
    }


    public static void generateImage(String file, String path) {
        try {
            // 去掉base64前缀 data:image/jpeg;base64,
            file = file.substring(file.indexOf(",", 1) + 1, file.length());
            byte[] b = Base64.decode(file);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
        } catch (IOException e) {

        }
    }

}
